<template>
  <div class="addrPage">
    <van-nav-bar
      title="地址列表"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    >
    </van-nav-bar>
    <van-address-list
      v-model="chosenAddressId"
      switchable
      :list="list"
      :disabled-list="disabledList"
      disabled-text="以下地址超出配送范围"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    />
  </div>
</template>
<script>
export default {
  name: "Address",
  data() {
    return {
      chosenAddressId: "1",
      list: [],
      disabledList: [
        {
          id: "3",
          name: "王五",
          tel: "1320000000",
          address: "浙江省杭州市滨江区江南大道 15 号",
        },
      ],
    };
  },
  computed: {},
  methods: {
    async getAddressInfo(values) {
      const data = await this.$store.dispatch("address/getAddress", values);
      //查询地址
      if (data.status === 500) {
        this.$notify({ type: "danger", message: "查询地址错误" });
      } else if (data.status === 200) {
        //查询成功
        data.data.forEach((item, index) => {
          let obj = {
            id: index,
            name: item.Name,
            tel: item.Phonenum,
            address: item.Address + item.AddressDetail,
            isDefault: item.Isdefault,
            Addressid: item.Addressid,
          };
          if (obj.isDefault) {
            this.list.unshift(obj);
          } else {
            this.list.push(obj);
          }
        });
      }
    },
    async onAdd(values) {
      this.$router.push("addressEdit");
    },
    async onEdit(item, index) {
      let address = this.$store.state.address.address;
      address = address.filter((it) => it.Addressid == item.Addressid);
      this.$router.push({
        name: "AddressEdit",
        params: { ...address[0], index },
      });
    },
    onSelect(item, index) {
      if (this.$route.query.flag) {
        this.$router.replace({
          name: "SubOrder",
          query: { id: item.Addressid, flag: "cart" },
        });
      }
    },
  },
  created() {
    this.getAddressInfo();
  },
  beforeRouteLeave(to, from, next) {  
    if (to.name === "SubOrder") {
      next();
      if (this.list.length == 0) {
        this.$router.push("/index");
      }
    } else {
      next();
    }
  },
};
</script>
<style scoped>
</style>